import threading
import urllib2

class PageUnit(threading.Thread):
	"""
	   Page Unit Class
	   Descirption:
	   	this class is the basis of python's threading module.

	   Usage:
	   1. inherit this class and define your fucntion and parameters.
		class stockpu(PageUnit):
			def prejob(self):
				self.args=("hello",)
				#or 
				self.kwargs={'str':'hello',}
			def ProcFunc(self,str):
		 		return str
		a=stockpu()
		a.start()
	   2. create an instance by using the method.
	   	def ryinfo(info):
			return info

		a=PageUnit()
		a.setProcFunc(ryinfo,"hello")
		a.start()

	  Reference:
	  	http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/
	"""
	def run(self):
		self.ack=0
		self.prejob()
		self.procedure()

	def prejob(self):
		return 0

	def procedure(self):
		self.data=self.ProcFunc(*self.args,**self.kwargs)
		self.ack=1
	
	def setProcFunc(self,func,*args, **kwargs):
		self.ProcFunc=func
		self.args=args
		self.kwargs=kwargs
		print args,kwargs
		#running directly
		#func(*args, **kwargs)

	def getAck(self):
		return self.ack

	def getData(self):
		return self.data

class StockPageUnit(PageUnit):
	"""
	   Stock Page Unit  
	"""
	def myprejob(self,StkNo):
		self.args=()
		self.kwargs={'URL':"http://mis.tse.com.tw/data/%s.csv",'StkNo':StkNo}

	def ProcFunc(self,URL,StkNo):
		#data source from TSE
		self.URL=URL%StkNo
		self.data=()
		page = urllib2.urlopen(self.URL)
		one_page=page.read()
		try:
     		   value =unicode(one_page, 'big5')
		except:
	  	   value = os.popen('echo "%s" |iconv -f big5 -t utf8 2>&1'%one_page).read()
		value=value.split(",")
		mydata=(value[-1].replace('"',''),value[8].replace('"',''))
		return mydata

class PageUnitSrv(threading.Thread):
	"""
 	   Page Unit Service	
	"""
	def run(self):
		self.done=0
		self.stocklist=[]
		for stock in self.StkNoList:
			thread_stock=StockPageUnit()
			thread_stock.myprejob(stock)
			thread_stock.start()
			self.stocklist.append(thread_stock)
		GETDATA=[]	
		while (1):
			Num=0
			for stock in self.stocklist:
				if stock.getAck():
					Num +=1
					stock_data=stock.getData()
					if stock_data not in GETDATA:
						GETDATA.append(stock_data)
						print stock_data[0]
			if Num==len(self.StkNoList):
				print 'Done'
				self.done=1
				break

	def setStocks(self,StkNoList):
		self.StkNoList=StkNoList

	def checkDone(self):
		return self.done
